package com.infocollect.project.grant.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentMap;

import com.infocollect.common.exception.CustomException;
import com.infocollect.common.utils.SecurityUtils;
import com.infocollect.common.utils.StringUtils;
import com.infocollect.common.utils.oss.OSSClientUtil;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.project.grant.domain.*;
import com.infocollect.project.grant.service.IGrExaminerGrantService;
import com.infocollect.project.grant.service.IGrGrantService;
import com.infocollect.project.grant.service.IGrUserCompanyService;
import com.infocollect.project.system.service.ISysConfigService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.infocollect.framework.aspectj.lang.annotation.Log;
import com.infocollect.framework.aspectj.lang.enums.BusinessType;
import com.infocollect.project.grant.service.IGrCompanyService;
import com.infocollect.framework.web.controller.BaseController;
import com.infocollect.framework.web.domain.AjaxResult;
import com.infocollect.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * 派出单位管理Controller
 *
 * @author infocollect
 * @date 2022-05-18
 */
@RestController
@RequestMapping("/grant/grcompany")
public class GrCompanyController extends BaseController
{
    @Autowired
    private IGrCompanyService grCompanyService;
    @Autowired
    private IGrUserCompanyService userCompanyService;
    @Autowired
    private IGrGrantService grantService;
    @Autowired
    private IGrCompanyService companyService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IGrExaminerGrantService grExaminerGrantService;
    @Autowired
    private OSSClientUtil ossClient;

    /**
     * 查询派出单位管理列表
     */
//    @PreAuthorize("@ss.hasPermi('grant:grcompany:list')")
    @GetMapping("/list")
    public AjaxResult list(GrCompany grCompany)
    {
        List<GrCompany> list = grCompanyService.selectGrCompanyList(grCompany);
        return AjaxResult.success(list);
    }

    /**
     * 导出派出单位管理列表
     */
    @PreAuthorize("@ss.hasPermi('grant:grcompany:export')")
    @Log(title = "派出单位管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(GrCompany grCompany)
    {
        List<GrCompany> list = grCompanyService.selectGrCompanyList(grCompany);
        ExcelUtil<GrCompany> util = new ExcelUtil<GrCompany>(GrCompany.class);
        return util.exportExcel(list, "grcompany");
    }

    /**
     * 获取派出单位管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('grant:grcompany:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(grCompanyService.selectGrCompanyById(id));
    }

    /**
     * 新增派出单位管理
     */
//    @PreAuthorize("@ss.hasPermi('grant:grcompany:add')")
    @Log(title = "派出单位管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GrCompany grCompany)
    {
        grCompany.setComCode(grCompany.getComName());
        return toAjax(grCompanyService.insertGrCompany(grCompany));
    }

    /**
     * 修改派出单位管理
     */
//    @PreAuthorize("@ss.hasPermi('grant:grcompany:edit')")
    @Log(title = "派出单位管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GrCompany grCompany)
    {
        return toAjax(grCompanyService.updateGrCompany(grCompany));
    }

    /**
     * 删除派出单位管理
     */
    @PreAuthorize("@ss.hasPermi('grant:grcompany:remove')")
    @Log(title = "派出单位管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for(int row=0;row<ids.length;row++){
            long comId = ids[row];
            GrCompany grCompany = new GrCompany();
            grCompany.setParentId(comId);
            List<GrCompany> grCompanys = grCompanyService.selectGrCompanyList(grCompany);
            if(grCompanys.size()>0){
                return AjaxResult.error("存在下级单位，不能删除");
            }
            GrExaminerGrantDto grExaminerGrantDto = new GrExaminerGrantDto();
            grExaminerGrantDto.setCompanyId(comId);
            List<GrExaminerGrantDto> list =  grExaminerGrantService.selectGrExaminerGrantDtoList(grExaminerGrantDto);
            if(list.size()>0){
                return AjaxResult.error("该派出单位下面已经有人报名，不能删除");
            }
            GrUserCompany userCompany = new GrUserCompany();
            userCompany.setCompanyId(comId);
            List<GrUserCompany> userCompanyList = userCompanyService.selectGrUserCompanyList(userCompany);
            if(userCompanyList.size()>0){
                return AjaxResult.error("该派出单位下面已经有管理员注册，不能删除");
            }
        }
        return toAjax(grCompanyService.deleteGrCompanyByIds(ids));
    }

    /**
     * 查询派出单位管理列表(不分页)
     */
    @GetMapping("/getCompanyList")
    public AjaxResult getCompanyList(GrCompany grCompany)
    {
        List<GrCompany> list = grCompanyService.selectGrCompanyList(grCompany);
        return AjaxResult.success(list);
    }
    /**
     * 导出首页派出单位
     */
    @Log(title = "导出派出单位信息", businessType = BusinessType.EXPORT)
    @GetMapping("/userCompanyPanelexport")
    public AjaxResult userCompanyPanelexport(UserCompanyPanelVo userCompanyPanelVo)
    {
        String registerUrl =userCompanyPanelVo.getRegisterUrl();
        AjaxResult result = getUserCompanyPanelData(userCompanyPanelVo);
        UserCompanyPanelVo userCompanyPanelVoResult = (UserCompanyPanelVo)result.get("data");
        GrCompanyExportDto companyExportDto = new GrCompanyExportDto();
        List<GrCompanyExportDto> companyExportDtoList = new ArrayList<>();

        List<GrCompany> companyList =userCompanyPanelVoResult.getCompanyList();
        companyList.stream().forEach(company->{
            GrCompanyExportDto companyExportDtoFor = new GrCompanyExportDto();
            companyExportDtoFor.setComCode(company.getComCode());
            companyExportDtoFor.setComName(company.getComName());
            companyExportDtoFor.setPlannedQuantity(company.getPlannedQuantity());
            companyExportDtoFor.setLvl(company.getLvl());
            //registerUrl+"/userregister?companyId="+row.id+"&grantId="+row.grantId;
            String registerUrlExport = registerUrl+"/userregister?companyId="+company.getId()+"&grantId="+company.getGrantId();
            companyExportDtoFor.setRegisterUrl(registerUrlExport);
            companyExportDtoList.add(companyExportDtoFor);

        });
        ExcelUtil<GrCompanyExportDto> util = new ExcelUtil<GrCompanyExportDto>(GrCompanyExportDto.class);
        return util.exportExcel(companyExportDtoList, "userCompanyPanelexport");
    }
    /**
     * 获取首页相关派出单位的统计信息
     * @return
     */
    @PostMapping("/getUserCompanyPanelData")
    public AjaxResult getUserCompanyPanelData(UserCompanyPanelVo userCompanyPanelVo){
        String enrollHost =  configService.selectConfigByKey("enroll_host");
        userCompanyPanelVo.setEnrollHost(enrollHost);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long grantId = userCompanyPanelVo.getGrantId();
        if(SecurityUtils.isInfocollectAdmin(userId)){
            //如果是管理员，走管理员单独的统计逻辑
            userCompanyPanelVo.setLvl(1);
            return getUserCompanyPanelDataForAdmin(userCompanyPanelVo);
        }
        GrUserCompany userCompany = new GrUserCompany();
        userCompany.setUserId(userId);
        userCompany.setGrantId(grantId);
        List<GrUserCompany> userCompanyList = userCompanyService.selectGrUserCompanyList(userCompany);
        if(userCompanyList.size()<=0){
            return AjaxResult.error("没有找到派出单位相关数据");
        }
        userCompany = userCompanyList.get(0);
        Long userCompanyId = userCompany.getCompanyId();
        GrCompany company = companyService.selectGrCompanyById(userCompanyId);
        if(company==null){
            return AjaxResult.error("没有找到派出单位相关数据");
        }
        Integer companyLvl= company.getLvl();
        if(companyLvl==1){
           return getUserCompanyPanelDataForAdmin(userCompanyPanelVo);
        }

        userCompanyPanelVo.setCompanyName(company.getComName());
        userCompanyPanelVo.setPlannedQuantity(company.getPlannedQuantity());
        if(companyLvl==2){
            userCompanyPanelVo.setParentId(company.getId());
            userCompanyPanelVo.setFormCompanyId(company.getId());
            return getUserCompanyPanelDataForLvl2(userCompanyPanelVo);
        }
        if(companyLvl==3){
            userCompanyPanelVo.setCompanyId(company.getId());
            return getUserCompanyPanelDataForLvl3(userCompanyPanelVo);
        }
        return AjaxResult.error("未找到相关配置信息");
    }

    /**
     * 管理员获取统计数据
     * @return
     */
    public AjaxResult getUserCompanyPanelDataForAdmin(UserCompanyPanelVo userCompanyPanelVo){
        //plannedQuantity  计划数
        //enrollQuantity   报名数
//        companyList  派出单位列表
        GrCompany company = new GrCompany();
        company.setGrantId(userCompanyPanelVo.getGrantId());
        company.setLvl(1);
        List<GrCompany> grCompanyList = companyService.selectGrCompanyList(company);
        company = grCompanyList.get(0);  //这里是获得本次报名的顶级派出单位(一般是杭州考试院)


        userCompanyPanelVo.setParentId(company.getId());
        userCompanyPanelVo.setLvl(2);
        List<GrCompany> companyList = companyService.selectGrCompanyCountList(userCompanyPanelVo);
        Long enrollQuantity = 0l;
        Integer plannedQuantity = 0;
        for(GrCompany tmp:companyList){
            enrollQuantity = tmp.getEnrollQuantity()+enrollQuantity;
            plannedQuantity += tmp.getPlannedQuantity();
        }
        userCompanyPanelVo.setCompanyName(company.getComName());
        userCompanyPanelVo.setEnrollQuantity(enrollQuantity);
        userCompanyPanelVo.setCompanyList(companyList);
        userCompanyPanelVo.setLvl(1);
//        userCompanyPanelVo.setPlannedQuantity(company.getPlannedQuantity());
        userCompanyPanelVo.setPlannedQuantity(plannedQuantity);
        userCompanyPanelVo.setFormCompanyId(company.getId());
        return AjaxResult.success(userCompanyPanelVo);
    }

    /**
     * 二级派出单位首页相关统计
     * @return
     */
    public AjaxResult getUserCompanyPanelDataForLvl2(UserCompanyPanelVo userCompanyPanelVo){
        userCompanyPanelVo.setLvl(3);
        List<GrCompany> companyList = companyService.selectGrCompanyCountList(userCompanyPanelVo);
        Long enrollQuantity = 0l;
        Integer plannedQuantity = 0;

        for(GrCompany tmp:companyList){
            enrollQuantity = tmp.getEnrollQuantityLvl()+enrollQuantity;
            try {
                plannedQuantity += tmp.getPlannedQuantity();
            }catch(Exception ex){}
            tmp.setEnrollQuantity(tmp.getEnrollQuantityLvl());
        }
        userCompanyPanelVo.setEnrollQuantity(enrollQuantity);
        userCompanyPanelVo.setCompanyList(companyList);
        userCompanyPanelVo.setLvl(2);
        userCompanyPanelVo.setPlannedQuantity(plannedQuantity);
        return AjaxResult.success(userCompanyPanelVo);
    }
    /**
     * 三级派出单位首页相关统计
     * @return
     */
    public AjaxResult getUserCompanyPanelDataForLvl3(UserCompanyPanelVo userCompanyPanelVo){
        userCompanyPanelVo.setLvl(3);
        List<GrCompany> companyList = companyService.selectGrCompanyCountList(userCompanyPanelVo);
        Long enrollQuantity = 0l;
        Integer plannedQuantity = 0;
        for(GrCompany tmp:companyList){
            enrollQuantity = tmp.getEnrollQuantityLvl()+enrollQuantity;
            try {
                plannedQuantity += tmp.getPlannedQuantity();
            }catch (Exception ex){}
            tmp.setEnrollQuantity(tmp.getEnrollQuantityLvl());
        }
        userCompanyPanelVo.setEnrollQuantity(enrollQuantity);
        userCompanyPanelVo.setCompanyList(companyList);
        userCompanyPanelVo.setLvl(3);
        userCompanyPanelVo.setPlannedQuantity(plannedQuantity);
        return AjaxResult.success(userCompanyPanelVo);
    }

    /**
     * 派出单位导入模版下载
     * @return
     * @throws IOException
     */
    @GetMapping("/getCompanyImportTemplate")
    public AjaxResult getCompanyImportTemplate() throws IOException {
        List<GrCompanyImport> list = new ArrayList<>();
        GrCompanyImport temp = new GrCompanyImport();
        temp.setComName("派出单位名称");
        list.add(temp);

        ExcelUtil<GrCompanyImport> util = new ExcelUtil<GrCompanyImport>(GrCompanyImport.class);
        return util.exportExcel(list, "导入模板");
    }
    /**
     * 导入派出单位
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("importComapny")
    public AjaxResult importComapny(MultipartFile file, Long grantId,Long comParentId,Integer lvl) throws Exception{
        if(grantId == null){
            return AjaxResult.error("错误的项目信息！");
        }
        if(comParentId == null){
            return AjaxResult.error("错误的派出单位信息！");
        }
        if(file ==null){
            return AjaxResult.error("错误的文件信息！");
        }
        ExcelUtil<GrCompanyImport> util = new ExcelUtil<GrCompanyImport>(GrCompanyImport.class);
        List<GrCompanyImport> comList = util.importExcel(file.getInputStream());
        for(int row=0,size = comList.size();row<size;row++){
            GrCompanyImport companyImport = comList.get(row);
            GrCompany company = new GrCompany();
            company.setComName(companyImport.getComName());
            company.setParentId(comParentId);
            company.setPlannedQuantity(0);
            company.setLvl(lvl+1);
            company.setIsEnabled("Y");
            company.setGrantId(grantId);
            List<GrCompany> grCompanys= grCompanyService.selectGrCompanyList(company);
            if(grCompanys.size()==0) {
                add(company);
            }else{
                company = grCompanys.get(0);
                grCompanyService.updateGrCompany(company);
            }
        }
        return AjaxResult.success();
    }
    /**
     * 上传报名清单盖章件
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/confirmFileUpload")
    public AjaxResult confirmFileUpload(MultipartFile file, Long grantId,Long comParentId) throws Exception{
        logger.info("grantId:"+grantId.toString()+"comParentId:"+comParentId.toString());
        if(grantId == null){
            return AjaxResult.error("错误项信息！");
        }
        if(comParentId == null){
            return AjaxResult.error("错误的派出单位信息！");
        }
        String filePath = ossClient.createFileDir("image","000000")+file.getOriginalFilename();
        String url = ossClient.uploadFile2OSS(file.getInputStream(),filePath);
//        logger.info("filePath:"+filePath);
//        logger.info("url:",url);
        GrCompany company =  grCompanyService.selectGrCompanyById(comParentId);
        company.setConfirmFileurl(filePath);
        grCompanyService.updateGrCompany(company);
//        String imgUrl = ossClient.getnbImgUrl(filePath);
//        logger.info("imgUrl:"+imgUrl);
        return AjaxResult.success();
    }
    @ResponseBody
    @PostMapping("/downloadConfirmfile")
    public AjaxResult downloadConfirmfile(String confirmFileurl) throws Exception{
        if(StringUtils.isEmpty(confirmFileurl)){
            return AjaxResult.error("用户未上传对应清单");
        }
        String imgUrl = ossClient.getnbImgUrl(confirmFileurl);
        return AjaxResult.success(imgUrl);
    }
}
